package database;


import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;

import configuration.TableConfiguration;

public  class DataBaseProcessor {
	
	/*Method used for getting value from database.
	 * Assuming it will return only one row per query.
	 * Assuming first entry in the HashMap is always a  primary key
	 */
	public ArrayList<Object> getDataFormDb(String tableName,Integer primaryKey){
		
		LinkedHashMap<String,String> columnNameAndDataType = TableConfiguration.addTableConfiguration(tableName);
		String query = "select * from "+tableName+" where "+columnNameAndDataType.keySet().iterator().next()+" = "+primaryKey+"";
		System.out.println(query);
		Statement st = null; 
		ResultSet rs = null;
		ArrayList<Object> columnData = new ArrayList<Object>();
		try {
			st = DbConnection.getConnection().createStatement();
			rs = st.executeQuery(query); 
			while(rs.next()){
			 
			 for(String columnName : columnNameAndDataType.keySet()){
				 columnData.add(rs.getObject(columnName));
			 }
		 }
		}
		 catch(Exception e){
			 e.printStackTrace();
		 }
		
		return columnData;
		
	}
	
	/*method used for inserting data in database . Assuming List contains column value in order as they are in DB*/
	public void insertDataInDb(String tableName,ArrayList<Object> columnValue){
		
		String query = "insert into "+tableName+" values ("+value(columnValue)+")";
		System.out.println(query);
		Statement st = null; 
		try {
			st = DbConnection.getConnection().createStatement();
			st.execute(query); 
		 }
		 catch(Exception e){
			 e.printStackTrace();
		 }
	}
	private String value(ArrayList<Object> columnValue) {
		String s = "";
		for(Object o :columnValue){
			s = s+"'"+o+"'"+",";
		}
		return s.substring(0,s.length()-1);
	}

}
